<template>
  <div>
    <me-table :data="state.list" :pagination="pagination" @current-change="pageSizeChange" :handle="{
      edit: () => {},
      delete: () => {}
    }">
      <!-- <el-table-column prop="avatar" label="头像" width="180" /> -->
      <el-table-column label="头像" width="180">
        <template #default="{ row }">
          <el-image class="img" :src="row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="roleType" label="角色">
        <template #default="{ row }">
          <div style="display: flex; align-items: center">
            {{ roleTypes[row.roleType] }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="roleType" label="状态">
        <template #default="{ row }">
          <div>
            <el-tag :type="row.state ? 'success' : 'danger'">{{ userState[row.state] }}</el-tag>
            <el-switch :value="mapUserState[row.state]" @change="($event: boolean) => stateChange($event, row._id)"></el-switch>
          </div>
        </template>
      </el-table-column>
    </me-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive } from 'vue';
import { getUserList, editUser } from '@/axios/api/user'
import { roleTypes, userState } from '@/enum'

const state = reactive({
  list: <{_id: string}[]>[]
})

type MapUserState = {
  [propName: number | string]: Boolean | number
}
const mapUserState: MapUserState = {
  0: false,
  1: true,
  'false': 0,
  'true': 1
}

const pagination = reactive({
  total: 0,
  index: 1,
  size: 20
})

const getList = () => {
  getUserList(pagination.index, pagination.size).then((res: any) => {
    state.list = res.records
    pagination.total = res.total
  })
}

onMounted(() => {
  getList()
})

const pageSizeChange = (index: number) => {
  pagination.index = index
  getList()
}

const stateChange = (newVal: boolean, id: string) => {
  console.log(newVal, id)
  const newState = <number>mapUserState[newVal.toString()]
  editUser(id, newState).then(() => {
    state.list = state.list.map(item => {
      if(item._id === id) {
        return {
          ...item,
          state: newState
        }
      }
      return item
    })
  })
}
</script>

<style scoped>
</style>